'''

@author: wyndem
@Emil:   wyndem@qq.com
@FileName: views.py
@Time: 2019/2/22 10:14
@Software: PyCharm
@Description: 

'''
import time

from aiohttp import web

from db import vpnUtil
from db.mySqlUtil import  mysql
from db.sqlLiteUtil import User, Card, db, Notice, Version, Recording
from util.PasswordGenerator import getKey

@mysql
async def presence(request):
    """
    根据用户名判断是否存在记录
    :param request:
    :return:
    """
    data =await  request.post()
    data_response={"success":True,"data":True,"message":"成功"}
    try:
        ac=data['ac']
    except:
        data_response["data"]=False
        data_response["success"]=False
        data_response["message"]="请正确传入参数"
        return web.json_response(data_response)
    from db.sqlLiteUtil import getUserInfo
    user=getUserInfo(ac)

    if user!=None:
        data_response['data']=False
        data_response["success"] = False
    return web.json_response(data_response)

@mysql
@db.atomic()
async def addUser(request):
    """
    添加用户
    :param request:
    :return:
    """
    data =await  request.post()
    data_response={"success":True,"data":True,"message":"成功"}
    try:
        ac=data['ac']
        name=data['name']
        pwd=data['pwd']
        phone=data['phone']
    except:
        data_response["data"]=False
        data_response["success"]=False
        data_response["message"]="请正确传入参数"
        return web.json_response(data_response)
    from db.sqlLiteUtil import getUserInfo
    user=getUserInfo(ac)
    if user!=None:
        data_response['data']=False
        data_response["success"]=False
        data_response['message']="用户名已存在"
        return web.json_response(data_response)

    user=User(name=name,ac=ac,pwd=pwd,phone=phone,integral=0)
    user.save()
    try:
        i=vpnUtil.findByName(ac)
        if i == None:
            vpnUtil.creater(ac, pwd)
    except:
        pass

    return web.json_response(data_response)



@mysql
async def updataUser(request):
    """
    修改用户
    :param request:
    :return:
    """
    data =await  request.post()
    data_response={"success":True,"data":True,"message":"成功"}
    try:
        ac=data['ac']
        name=data['name']
        pwd=data['pwd']
        phone=data['phone']
    except:
        data_response["data"]=False
        data_response["success"]=False
        data_response["message"]="请正确传入参数"
        return web.json_response(data_response)

    i = User.select().where(User.phone == phone)
    if i.count() != 0 and i.get().phone!="" and i.get().ac!=ac:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "联系方式已存在"
        return web.json_response(data_response)


    try:
        user= User.get(User.ac == ac,User.pwd == pwd)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "账号或密码错误"
        return web.json_response(data_response)

    if user==None:
        data_response['data']=False
        data_response["success"]=False
        data_response['message']="用户不存在"
        return web.json_response(data_response)
    user.name=name
    user.phone=phone
    user.save()
    return web.json_response(data_response)

@mysql
async def getUserInfo(request):
    """
    查询用户金额和手机号码
    :param request:
    :return:
    """
    data_response = {"success": True, "data": {"money":None,"phone":None,'maxll':None,'sentll':None}, "message": "成功"}
    ac = request.query.get('ac')
    if ac==None:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "ac不能为空"
        return web.json_response(data_response)
    try:
        user=User.get(User.ac==ac)
        ua=vpnUtil.findByName(ac)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "该账户不存在"
        return web.json_response(data_response)

    data_response["data"]["money"]=user.integral
    data_response["data"]["phone"]=user.phone
    data_response["data"]["sentll"]=int(ua[2]/1024/1024)+int(ua[3]/1024/1024)
    data_response["data"]["maxll"]=int(ua[4]/1024/1024)
    return web.json_response(data_response)

@mysql
@db.atomic()
async def recharge(request):
    """
    充值接口
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    data =await  request.post()
    try:
        ac=data['ac']
        key=data['key']
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "参数缺少"
        return web.json_response(data_response)
    #查询卡密是否存在
    try:
        card = Card.get(Card.key == key)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "卡密不正确"
        return web.json_response(data_response)
    if not card.available:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "卡密已被使用"
        return web.json_response(data_response)
    from db.sqlLiteUtil import getUserInfo
    user = getUserInfo(ac)
    user.integral=int(card.value)+int(user.integral)
    card.available=False
    card.save()
    user.save()
    recording=Recording(card=card.key,ac=user.ac,phone=user.phone,type='手动',value=card.value,createDate=time.strftime("%F-%H:%M:%S"))
    recording.save()
    return web.json_response(data_response)

@mysql
async def announcement(request):
    """
    获取通知
    :param request:
    :return:
    """
    data_response = {"success": True, "data": False,"titile": "通知", "message": "暂无通知"}
    try:
        notice =Notice.get()
    except:
        return web.json_response(data_response)
    data_response['data']=True
    data_response['titile']=notice.title
    data_response['message']=notice.message
    return web.json_response(data_response)

@mysql
@db.atomic()
async def consumption(request):
    """
    消费
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    data = await  request.post()
    try:
        ac=data['ac']
        pwd=data['pwd']
        try:
            value=int(data['value'])
        except:
            data_response['data'] = False
            data_response["success"] = False
            data_response['message'] = "消费分数不正确"
            return web.json_response(data_response)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "参数缺少"
        return web.json_response(data_response)

    if int(value)<=0:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "消费分数不正确"
        return web.json_response(data_response)

    try:
        user= User.get(User.ac == ac,User.pwd == pwd)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "该用户不存在"
        return web.json_response(data_response)

    money=user.integral
    remaining=int(money)-int(value)
    if remaining < 0:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "余额不足"
        return web.json_response(data_response)
    user.integral=remaining
    user.save()
    return web.json_response(data_response)


@mysql
async def version(request):
    """
    获取版本
    :param request:
    :return:
    """
    data_response = {"success": False, "data": {"url":None,"message":None,"code":None}}
    try:
        version =Version.get()
    except:
        return web.json_response(data_response)
    data_response['data']={
        "url": version.url,
        "message": version.description,
        "code": version.code
    }
    data_response['success']=True

    return web.json_response(data_response)


@mysql
async def exceptSave(request):
    """
    出现异常
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True}
    try:
        data = await  request.post()
        ex=data.get("ex")
        with open("except.log", "a", encoding='utf-8') as f:
            f.write('------' + time.strftime("%F-%H:%M:%S") + '-------\n')
            f.write(str(ex))
            f.write('\n\n-------------End------------------------\n\n\n\n\n\n\n\n')
    except:
        return web.json_response(data_response)

    return web.json_response(data_response)

@mysql
@db.atomic()
async def consumption_ll(request):
    """
    充流量
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    data = await  request.post()
    try:
        ac=data['ac']
        pwd=data['pwd']
        try:
            value=int(data['value'])
        except:
            data_response['data'] = False
            data_response["success"] = False
            data_response['message'] = "消费分数不正确"
            return web.json_response(data_response)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "参数缺少"
        return web.json_response(data_response)

    if value<=0 or value > 3 :
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "消费分数不正确"
        return web.json_response(data_response)

    try:
        user= User.get(User.ac == ac,User.pwd == pwd)

        money = user.integral
        remaining = int(money) - int(value)
        if remaining < 0:
            data_response['data'] = False
            data_response["success"] = False
            data_response['message'] = "余额不足"
            return web.json_response(data_response)
        user.integral = remaining
        user.save()
        # 5m    5242880   1
        # 15m    15728640  2
        # 30m    31457280  3
        tablejia = {1: 5242880, 2: 15728640, 3: 31457280}
        ll = tablejia[value]
        vpnUtil.updataMaxll(ac, ll)
    except:
        data_response['data'] = False
        data_response["success"] = False
        data_response['message'] = "该用户不存在"
        return web.json_response(data_response)

    return web.json_response(data_response)

@mysql
@db.atomic()
async def card(request):
    """
    生成卡密
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    ac = request.query.get('name')
    if ac==None or ac!="wen":
        return web.json_response(data_response)
    try:
        n = int(request.query.get('num'))
        m = int(request.query.get('money'))
    except:
        return web.json_response(data_response)
    if n > 10 or m > 50:
        return web.json_response(data_response)


    data = [{
        'key':getKey(),
        'value':m,
        'createDate':time.strftime("%F"),
        'available':True
    } for i in range(n)]

    txt=""
    with db.atomic():
        for i in range(0, n, 100):
           Card.insert_many(data[i:i + 100]).execute()
        for i in data:
            txt+=i['key']+"\n"
    return web.Response(text=txt)

@mysql
@db.atomic()
async def new_version(request):
    """
    发布版本
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    ac = request.query.get('name')
    if ac==None or ac!="wen":
        return web.json_response(data_response)
    code = request.query.get('code')
    url = request.query.get('url')
    description = request.query.get('description')
    if code==None or url==None or description==None:
        return web.json_response(data_response)



    try:
        version =Version.get()
    except:
        v=Version(code=code,url=url,description=description)
        v.save()
        return web.json_response(data_response)

    if version!=None:
        version.code=code
        version.url=url
        version.description=description
        version.save()
    return web.json_response(data_response)

@mysql
@db.atomic()
async def notice(request):
    """
    发布通知
    :param request:
    :return:
    """
    data_response = {"success": True, "data": True, "message": "成功"}
    ac = request.query.get('name')
    if ac==None or ac!="wen":
        return web.json_response(data_response)
    title = request.query.get('title')
    message = request.query.get('message')
    if title==None or message==None :
        return web.json_response(data_response)

    try:
        notice =Notice.get()
    except:
        n=Notice(title=title,message=message)
        n.save()
        return web.json_response(data_response)

    if notice!=None:
        notice.title=title
        notice.message=message
        notice.save()
    return web.json_response(data_response)